package com.cuckoo.service.impl;

import com.cuckoo.common.JuHe;
import com.cuckoo.dao.AuthCodeMapper;
import com.cuckoo.pojo.AuthCode;
import com.cuckoo.service.AuthCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
public class AuthCodeServiceImpl implements AuthCodeService {
    @Autowired
    private AuthCodeMapper authCodeMapper;

    @Override
    @Transactional
    public Integer addAuth(String phone,Integer type) {
        //先判断短信是否存在对应的记录
        AuthCode resultAuth=getAuthCodeByPhoneAndCodeAndType (phone,null,type);
        Integer code=new Random ().nextInt(999999);
        while(code<100000){
            code=new Random ().nextInt(999999);
        }
        if (resultAuth!=null){
            //存在这个记录（删除这条记录）
            authCodeMapper.deleteByPrimaryKey ( resultAuth.getId () );
        }
        //发送短信
       // JuHe.getCodeSms ( phone,code);
        //入库
        AuthCode authCode=new AuthCode ();
        authCode.setCellphone ( phone );
        authCode.setCreatetime ( System.currentTimeMillis ()/1000);
        authCode.setSignInNo ( code.toString () );
        authCode.setType ( type );
        return authCodeMapper.insertSelective ( authCode );
    }

    @Override
    public AuthCode getAuthCodeByPhoneAndCodeAndType(String phone , String code , Integer type) {
        return authCodeMapper.getAuthCodeByPhoneAndCodeAndType ( phone,code,type);
    }
}
